<template>
  <div class="departments">
    <el-card class="box-card">
      <!-- tabs -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="组织结构" name="first">
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="6">
              <h5>后台管理系统</h5>
            </el-col>
            <el-col :span="12" />
            <el-col :span="6" style="text-align: right">
              <span class="leader">负责人</span>
              <el-dropdown>
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item><el-button
                    type="text"
                    @click="AddDialogForm('')"
                  >添加子部门</el-button></el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
          <el-divider />

          <!-- 部门管理 -->
          <el-tree :data="departs" :props="defaultProps">
            <el-row
              slot-scope="{ data }"
              style="flex: 1"
              type="flex"
              justify="space-between"
            >
              <el-col :span="6">
                <span>{{ data.name }}</span>
              </el-col>
              <el-col :span="6" style="text-align: right">
                <span class="leader">{{ data.manager }}</span>
                <el-dropdown>
                  <span class="el-dropdown-link">
                    操作<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item><el-button
                      type="text"
                      @click="AddDialogForm(data.id)"
                    >添加子部门</el-button></el-dropdown-item>

                    <el-dropdown-item><el-button
                      type="text"
                      @click="EditDialogForm(data)"
                    >编辑部门</el-button></el-dropdown-item>

                    <el-dropdown-item><el-button
                      type="text"
                      @click="deleteDepartment(data.id)"
                    >删除部门
                    </el-button></el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </el-tree>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="部门名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门编码"
          :label-width="formLabelWidth"
          prop="code"
        >
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门负责人"
          :label-width="formLabelWidth"
          prop="manager"
        >
          <el-select
            v-model="form.manager"
            placeholder="请选择负责人"
            @focus="getEmployees"
          >
            <el-option
              v-for="item in departmentHeadList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="部门介绍"
          :label-width="formLabelWidth"
          prop="introduce"
        >
          <el-input v-model="form.introduce" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDepartment">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  departs,
  addDeparts,
  editDeparts,
  queryDeparts,
  deleteDeparts
} from '@/api/departments'
import { getEmployees } from '@/api/employees'
export default {
  name: 'Departments',
  data() {
    return {
      activeName: 'first',
      // label控制tree的左边,children控制右边
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 部门管理的数据
      departs: [],
      // 控制dialog弹窗
      dialogFormVisible: false,
      // 表单数据
      form: this.initForm(),
      //  {
      //   code: '', // 部门编码，同级部门不可重复
      //   introduce: '', // 介绍
      //   manager: '', // 负责人名称
      //   name: '', // 部门名称
      //   pid: '', // 父级部门ID
      //    id: ''
      // }
      // 表单宽度
      formLabelWidth: '120px',
      // 部门负责人
      departmentHeadList: [],
      // 表单验证
      rules: {
        code: [
          { required: true, message: '输入不能为空' },
          { min: 1, max: 50, message: '长度为1-50' }
        ],
        introduce: [
          { required: true, message: '输入不能为空' },
          { min: 1, max: 300, message: '长度为1-300' }
        ],
        manager: [{ required: true, message: '不能为空' }],

        name: [
          { required: true, message: '输入不能为空' },
          { min: 1, max: 50, message: '长度为1-50' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getDepart()
  },
  methods: {
    // 递归组织架构
    recursiveDepart(root, res) {
      // 将第二层的数据加到root的children重
      if (root && root.length) {
        root.forEach((v) => {
          v.children = res.filter((vc) => v.id == vc.pid)
          this.recursiveDepart(v.children, res)
        })
      }
    },
    // 初始化form
    initForm() {
      return {
        code: '', // 部门编码，同级部门不可重复
        introduce: '', // 介绍
        manager: '', // 负责人名称
        name: '', // 部门名称
        pid: '', // 父级部门ID
        id: ''
      }
    },
    // 获取部门列表
    async getDepart() {
      // 解构出res部门数组
      const {
        data: { depts: res }
      } = await departs()
      // 删除掉第一个元素,因为pid为-1
      res.shift()
      // 过滤出v.pid不为空的数组
      const root = res.filter((v) => !v.pid)

      this.recursiveDepart(root, res)
      this.departs = root
    },

    // 获取负责人数据
    async getEmployees() {
      const { data: res } = await getEmployees()
      this.departmentHeadList = res
    },

    // 点击添加弹窗
    AddDialogForm(val) {
      //  弹出弹窗
      this.dialogFormVisible = true
      // 将表单清空
      Object.assign(this.form, this.initForm())
      // 由于一弹窗会触发表单验证，所以可以重置一次表单
      this.$refs.form.resetFields()
      // 将pid的值赋给form的pid
      this.form.pid = val
    },
    // 点击编辑弹窗
    async EditDialogForm(data) {
      //  弹出弹窗
      this.dialogFormVisible = true
      const res = await queryDeparts(data.id)
      Object.assign(this.form, res.data)
    },
    // 验证通过时,添加部门
    addDepartment() {
      this.$refs.form.validate(async(flag) => {
        if (flag) {
          // 如果有id则为编辑函数
          if (this.form.id) {
            var res = await editDeparts(this.form)
          } else {
            // 如果没有id，则为新增部门
            var res = await addDeparts(this.form)
          }
          // 弹出成功提示
          this.$message.success(res.message)
          // 重新请求部门列表
          this.getDepart()
          // 退出弹出框
          this.dialogFormVisible = false
          // 清空表单数据
          this.$refs.form.resetFields()
        } else {
          // 弹出失败提示
          this.$message.error('输入格式有误')
          return false
        }
      })
    },

    // 删除部门
    deleteDepartment(id) {
      this.$confirm('正在删除部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await deleteDeparts(id)
          this.$message({
            type: 'success',
            message: res.message
          })
          this.getDepart()
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  .el-card {
    padding: 20px;
    padding-top: 0;

    .row-bg {
      h5 {
        margin: 0;
      }
    }
  }
  .leader {
    font-size: 14px;
    margin-right: 1.666667rem;
  }
  .el-tab-pane {
    padding: 1.666667rem 1.666667rem 0;
  }
}
</style>
